package Sparse_Arrays_01;

/*
 * @Author 罗
 * @date 2020/3/10 - 9:15 下午
 *
 */

import Sparse_Arrays_01.Entity.FieldMapping;
import Sparse_Arrays_01.Entity.ChestData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ReadXmlFile {
public static final String XML_FILE_PATH = "/Users/luo/Desktop/chess.xml";

    public List<ChestData> readXml(){
        List<ChestData> parse = new ArrayList<>();

        Field[] fields = ChestData.class.getDeclaredFields();

        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(XML_FILE_PATH);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElement = document.getRootElement();
        Iterator<Element> chess = rootElement.elementIterator();
        while(chess.hasNext()){
            ChestData chestData = new ChestData();
            Element firstOrder = chess.next();
            Iterator<Element> secondOrder = firstOrder.elementIterator();
            while(secondOrder.hasNext()){
                Element sonElement = secondOrder.next();
                String tagName = sonElement.getName();

                for (Field field : fields) {
                    field.setAccessible(true);
                    if(field.getDeclaredAnnotation(FieldMapping.class).name().contentEquals(tagName)){
                        String data = sonElement.getStringValue();
                        try {
                            field.set(chestData,Integer.valueOf(data));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            parse.add(chestData);
        }
        return parse;
    }
}
